<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Library\WxNotify;
use App\Library\WxPay;
use App\Models\video\CommonServer;
use App\Models\video\CourseModel;
use App\Models\video\LevelModel;
use App\Models\video\OrderModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VideoUserModel;
use App\Models\video\VodVideoModel;
use Illuminate\Http\Request;

class PayController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['wxNotify']; //不校验openid
        parent::__construct($request);
    }

    public function getBuyPrice($payMoney, $payMode, $memberMode, $userId){
        if($payMode == "0"){
            $payMoney = 0;
        }elseif($payMode == "2"){ // 会员免费
//            if($userId){
//                $userData = VideoUserModel::getFields("level_id,level_time", ["id" => $userId], true, false);
//                if((!empty($userData["levelId"]) && $userData["levelTime"] > time())){
//                    $payMoney = 0;
//                }
//            }
        }else{ // 付费
            if($memberMode != '0') { // 会员折扣
                $settingData = VideoSettingModel::getFields("open_member,member_discount", ["mall_id" => request()->mallData["id"]], true, false);
                if($settingData["openMember"] == '1' && !empty($settingData["memberDiscount"])) {
                    $userData = VideoUserModel::getFields("level_id,level_time", ["id" => $userId], true, false);
                    if((!empty($userData["levelId"]) && $userData["levelTime"] > time())) {
                        $payMoney = $payMoney * $settingData["memberDiscount"] / 100;
                    }
                }
            }
        }
        return CommonServer::price_format($payMoney);
    }

    public function applyPay(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->type){
            return $this->return_result(ErrorCode::code("params_not_exist", "类型"));
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", $request->type == '1' ? "视频ID" : "课程ID"));
        }
        if($request->type == '3'){ // 会员
            $data = LevelModel::getFields("name,pay_money", ["id" => $request->id], true, false);
            if(empty($data)){
                return $this->return_result(ErrorCode::code("customized", "id错误"));
            }
            $data["title"] = $data["name"];
            $data["payMoney"] = CommonServer::price_format($data["payMoney"]);
        }else{
            if($request->type == '1'){ // 视频
                $data = VodVideoModel::getFields("title,pay_money,pay_mode,member_mode", ["id" => $request->id], true, false);
            }elseif($request->type == '2'){ // 课程
                $data = CourseModel::getFields("name as title,pay_money,pay_mode,member_mode", ["id" => $request->id], true, false);
            }else{
                return $this->return_result(ErrorCode::code("customized", "type错误"));
            }
            if(empty($data)){
                return $this->return_result(ErrorCode::code("customized", "数据错误"));
            }
            $data["payMoney"] = $this->getBuyPrice($data["payMoney"], $data["payMode"], $data["memberMode"], $request->userLoginData["id"]);
        }
        if($data["payMoney"] <= 0){
            return $this->return_result(ErrorCode::code("customized", "金额错误"));
        }
        $orderData = OrderModel::getFields("id,order_sn,status,type", ["mall_id" => $request->mallData["id"], "user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => $request->type]);
        if(!empty($orderData) && ($orderData["type"] != '3' || in_array($orderData["status"], [2,4,5]))){
            if(in_array($orderData["status"], [2,4,5])) {
                return $this->return_result(ErrorCode::code("customized", "您已付费了"));
            }
            $orderSn = date('YmdHis') . rand(1000, 9999);
            OrderModel::doUpdate(["order_sn" => $orderSn, "money" => $data["payMoney"]], ["id" => $orderData["id"]]);
            $id = $orderData["id"];
        }else{
            $orderSn = date('YmdHis') . rand(1000, 9999);
            $id = OrderModel::toAdd(["order_sn" => $orderSn, "money" => $data["payMoney"], "user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => $request->type, "status" => 1], true);
        }
        $payData = [
            "total_fee" => $data["payMoney"] * 100, "openid" => $request->userLoginData["openid"],
//            "total_fee" => 0.01 * 100,
            "out_trade_no" => $orderSn, "body" => $data["title"],
            "attachData" => json_encode(["type" => $request->type, "orderId" => $id], JSON_UNESCAPED_UNICODE)
        ];
        $type = $request->appPlatform ?: "wx";
        if($type == "qq"){
            $field = "qq_app_id,qq_app_secret,app_id,mch_id,mch_key";
        }else{
            $field = "app_id,mch_id,mch_key";
        }
        $settingData = VideoSettingModel::getFields($field, ["mall_id" => $request->mallData["id"]]);
        $payObject = new WxPay($settingData["appId"], $settingData["mchId"], $settingData["mchKey"]);
        global $scf_data;
        if (isset($scf_data["IS_SCF"]) && $scf_data["IS_SCF"] == true){
            $payData["notifyUrl"] = $scf_data['host'] . "/videoApi/pay/wxNotify"; //通知地址  确保外网能正常访问
        }else{
            $payData["notifyUrl"] = $_SERVER["REQUEST_SCHEME"] . '://'.$_SERVER['HTTP_HOST'] . "/videoApi/pay/wxNotify"; //通知地址  确保外网能正常访问
        }
        if($type == "qq"){
            $res = $payObject->toQQPay($payData, $settingData, $msg);
        }else {
            $res = $payObject->toPay($payData, $msg);
        }
        if($res){
            $this->returnData['data'] = $res;
            return $this->return_result($this->returnData);
        }else{
            return $this->return_result(ErrorCode::code("customized", $msg));
        }
    }

    // 微信支付回调
    public function wxNotify(){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $notify = new WxNotify();
        $result = $notify->handleNotify();
        return response()->json($result);
    }
}
